package main

import (
	"fmt"
	ziface "zinx/Ziface"
	znet "zinx/Znet"
)

// ping test 自定义路由
type PingRouter struct {
	znet.BaseRouter
}

func (this *PingRouter) Handler(request ziface.IRuquest) {

	fmt.Println("Call Router Handler")
	//读取客户端的数据
	//打印日志
	fmt.Println("recv from client :msgid=", request.GetConnection().GetID(), "data= ", string(request.GetData()))
	err := request.GetConnection().SendMsg(200, []byte("ping....ping....ping......"))
	if err != nil {
		fmt.Println("send msg err", err)
	}
}

type HelloRouter struct {
	znet.BaseRouter
}

func (this *HelloRouter) Handler(request ziface.IRuquest) {

	fmt.Println("Call Router Handler")
	//读取客户端的数据
	//打印日志
	fmt.Println("recv from client :msgid=", request.GetConnection().GetID(), "data= ", string(request.GetData()))
	err := request.GetConnection().SendMsg(201, []byte("Hello zinx!"))
	if err != nil {
		fmt.Println("send msg err", err)
	}
}

func beforestart(con ziface.IConnection) {
	fmt.Println("-----> DoConnectionBegin is called <-------")
	if err := con.SendMsg(202, []byte("Doconnection before")); err != nil {
		fmt.Println("DoConnectionBegin err: ", err)
	}

	con.SetProperty("Name", "shadowdance")
	con.SetProperty("Address", "https://gitee.com/shadow-man")
	con.SetProperty("Server", "zinxv.1.0")
	con.SetProperty("Time", "2023-03-02")
}

func afterstop(con ziface.IConnection) {
	fmt.Println("-----> DoConnectionLost is called <-------")
	fmt.Println("connid=", con.GetID(), "is lost....")
	if value, err := con.GetProperty("Name"); err == nil {
		fmt.Println("Name: ", value)
	} else {
		fmt.Println("err: ", err)
	}
	if value, err := con.GetProperty("Address"); err == nil {
		fmt.Println("Address: ", value)
	} else {
		fmt.Println("err: ", err)
	}

	if value, err := con.GetProperty("Server"); err == nil {
		fmt.Println("Server ", value)
	} else {
		fmt.Println("err: ", err)
	}

	if value, err := con.GetProperty("Time"); err == nil {
		fmt.Println("Time ", value)
	} else {
		fmt.Println("err: ", err)
	}
}

func main() {

	//1.创建一个server句柄
	s := znet.NewServer()

	s.AddRouter(0, &PingRouter{})
	s.AddRouter(1, &HelloRouter{})

	//为当前server添加对应的回调函数
	s.SetOnConnStart(beforestart)
	s.SetOnConnStop(afterstop)
	s.Serve()
	//启动Server
}
